//
//  SZChannelView.m
//  仿网易新闻
//
//  Created by made on 17/1/4.
//  Copyright © 2017年 made. All rights reserved.
//

#import "SZChannelView.h"
#import "SZChannelModel.h"
#import "SZChannelLabel.h"

const int baseTag = 666;

@interface SZChannelView ()

@property (nonatomic, strong)UIScrollView *scrolView;

@end


@implementation SZChannelView

- (id) initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self setupUI];
    }
    return self;
}




- (void) setChannelList:(NSArray *)channelList
{
    CGFloat origin = 0;
    NSInteger index = 0;
    for (SZChannelModel *model in channelList)
    {
        SZChannelLabel *lable = [SZChannelLabel labelWithText:model.tname];
        NSLog(@"%@",NSStringFromCGRect(lable.bounds));
    
        CGRect frame = CGRectMake(origin, 0, lable.bounds.size.width, self.bounds.size.height);
        lable.frame = frame;
        [_scrolView addSubview:lable];
        
        lable.tag = index + baseTag;
        
        //添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(channelClick:)];
        [lable addGestureRecognizer:tap];
        
        if (index == 0) lable.isSelected = YES;
        
        index += 1;
        
        origin += lable.bounds.size.width;
    }

    _scrolView.contentSize = CGSizeMake(origin, self.bounds.size.height);
}






- (void) setCurrentIndex:(NSInteger)currentIndex
{
    if (_currentIndex == currentIndex) return;
  
    //1.找到对应的currentIndex的lable.把它的颜色和字体改成高亮
    NSInteger tag = currentIndex + baseTag;
    SZChannelLabel *label = [_scrolView viewWithTag:tag];
    label.isSelected = YES;
    
    //1.1看其是否需要调整位置
    CGFloat lx = label.frame.origin.x;
    CGFloat lw = label.frame.size.width + lx;
    CGFloat cx = _scrolView.contentOffset.x;
    if (lx < cx || lw > cx)
    {
        [_scrolView scrollRectToVisible:label.frame animated:YES];
    }
    
    //2.把之前高亮的label改成正常的状态
    NSInteger oldTag = _currentIndex + baseTag;
    SZChannelLabel *oldLabel = [_scrolView viewWithTag:oldTag];
    oldLabel.isSelected = NO;
    
    //3.修改_currentIndex的值
    _currentIndex = currentIndex;
}



- (void) channelClick:(UITapGestureRecognizer *) tap
{
    SZChannelLabel *label = (SZChannelLabel *)tap.view;
    NSInteger index = label.tag - baseTag;
    [self setCurrentIndex:index];
    
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(channelChanged:)])
    {
        [self.delegate channelChanged:index];
    }
    
}



- (void) setupUI
{
    _scrolView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrolView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_scrolView];
}

@end
